package com.fbli.udp.homework;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/***
 * 接收端A
 */
public class Homework02ReceiverA {
    public static void main(String[] args) throws IOException {
        //创建一个DatagramSocket在9999端口接收数据
        DatagramSocket datagramSocket = new DatagramSocket(8888);
        //2.构建一个DatagramPacket对象，准备接收数据,一个数据包最大64k
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        //3.调用接收方法,将通过网络传输的DatagramPacket对象
        //填充到packet对象
        //当有数据发送到本记的9999端口时，就会接收到数据
        //如果没有数据包发送到本机9999端口，就会阻塞等待。
        System.out.println("接收端A等待接收对象");
        datagramSocket.receive(packet);
        //4.把packet进行拆包，取出数据，并显示。
        int length = packet.getLength();//实际接收到的数据长度
        byte[] data = packet.getData();//接收到数据
        String s = new String(data, 0, length);
        System.out.println(s);
        String replay;
        if("四大名著是哪些".equals(s)){
            replay="四大名著是<<红楼梦>>......";
        }else {
            replay="what?";
        }
        //向B回复信息
        data = replay.getBytes();
        packet = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.0.104"), 9998);
        datagramSocket.send(packet);
        //关闭资源
        datagramSocket.close();
        System.out.println("A端退出");
    }
}
